<?php
namespace Todo\Service;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class DictService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new DictService();

        return self::$__INSTANCE;
    }

    /**
     * 查询一个数据字典,并解析
     * @param string $dictCode 字典代码
     * @return bool|array
     */
   public function getDict($dictCode){
       $data = D('Todo/Sys/Dict')->findOne(array('code'=>$dictCode));

       if(!$data) return false;

       if($data['value']) $data['map'] = $this->mapValue($data['value']);

       return $data;
   }

    /**
     * 将一行一条的键值对形式变成关联数组k1=v1
     * @param string $content 内容
     * @return array|bool
     */
    public function mapValue($content){
        $rows = explode("\r", $content);
        if(!$rows) return false;
        $map = array();
        foreach ($rows as $row){
            if(!trim($row)) continue;
            $rd = explode('=', $row);
            $map[trim($rd[0])] = trim($rd[1]);
        }
        return  $map;
    }

    /**
     * 根据值查询某个数据字典的标题
     * @param string $dictCode 字典代码
     * @param string $val 字典的值
     * @return bool|string
     */
    public function getDictTitle($dictCode, $val){
        $data = $this->getDict($dictCode);
        if(!$data) return false;

        return $data['map'][$val];
    }
}